package com.zqweb.gulimall.authserver.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.zqweb.common.exception.ExpCodeAndMsgEnum;
import com.zqweb.common.utils.R;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class AuthSentinelConfig {
    // 自定义Sentinel的流控响应结果（针对的是被Sentinel控制阻塞后的请求）
    public AuthSentinelConfig(){
        WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
            @Override
            public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                R error = R.error(ExpCodeAndMsgEnum.REQ_TOOMANY_EXCEPTION.getCode(), ExpCodeAndMsgEnum.REQ_TOOMANY_EXCEPTION.getMsg());
                httpServletResponse.getWriter().println(JSON.toJSONString(error));
            }
        });

    }

}
